<template>
  <div class="command-container">
    <!-- 顶部信息卡片 -->
    <el-card class="video-info-card" shadow="hover">
      <div class="video-header">
        <div class="header-left">
          <i class="el-icon-video-camera"></i>
          <span class="title">视频命令配置</span>
        </div>
        <el-tag type="primary">BV号：{{ $route.query.videoBv }}</el-tag>
      </div>
      <div class="video-content">
        <div class="info-item">
          <span class="label">视频ID：</span>
          <span class="value">{{ $route.query.videoId }}</span>
        </div>
        <div class="info-item">
          <span class="label">BV号：</span>
          <span class="value">{{ $route.query.videoBv }}</span>
        </div>
      </div>
    </el-card>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <div class="left-btns">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['system:command:add']"
        >新增命令</el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="medium"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:command:remove']"
        >批量删除</el-button>
      </div>
      
      <div class="right-btns">
        <el-button
          type="info"
          icon="el-icon-refresh"
          size="medium"
          circle
          @click="handleQuery"
        ></el-button>
      </div>
    </div>

    <!-- 命令列表 -->
    <el-card class="command-list" shadow="hover">
      <el-table
        v-loading="loading"
        :data="commandList"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ background: '#f5f7fa' }"
        style="width: 100%"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="命令" align="center" prop="command">
          <template slot-scope="scope">
            <el-tag size="medium" type="success">{{ scope.row.command }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.remark" placement="top">
              <span class="remark-text">{{ scope.row.remark || '-' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              class="delete-btn"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加/修改对话框 -->
    <el-dialog 
      :title="title" 
      :visible.sync="open" 
      width="800px" 
      append-to-body
      :close-on-click-modal="false"
      custom-class="command-dialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="视频ID" prop="videoId">
          <el-input v-model="form.videoId" disabled class="disabled-input" />
        </el-form-item>
        <el-form-item label="视频BV号" prop="videoBv">
          <el-input v-model="form.videoBv" disabled class="disabled-input" />
        </el-form-item>
        <div class="command-tip">
          <i class="el-icon-info"></i>
          <span>提示：命令中可使用 <code>%pname%</code> 代替玩家ID</span>
          <el-button
            type="text"
            class="copy-btn"
            @click="copyVariable"
          >
            <i class="el-icon-document-copy"></i>
            复制变量
          </el-button>
        </div>
        <el-form-item label="命令" prop="command">
          <el-input 
            v-model="form.command" 
            placeholder="请输入命令，不需要带'/'"
            :maxlength="50"
            show-word-limit
            class="command-input"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :autosize="{ minRows: 3, maxRows: 6}"
            class="remark-input"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="medium" @click="submitForm">确 定</el-button>
        <el-button size="medium" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <page-footer />
  </div>
</template>

<script>
import { listCommand, getCommand, delCommand, addCommand, updateCommand } from "@/api/system/command";
import PageFooter from '@/components/Footer'

export default {
  name: "Command",
  components: {
    PageFooter
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频关联指令表格数据
      commandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        videoId: this.$route.query.videoId,
        videoBv: this.$route.query.videoBv
      },
      // 表单参数
      form: {
        id: null,
        videoId: null,
        videoBv: null,
        command: null,
        remark: undefined
      },
      // 表单校验
      rules: {
        videoId: [
          { required: true, message: "视频ID不能为空", trigger: "blur" }
        ],
        videoBv: [
          { required: true, message: "视频BV号不能为空", trigger: "blur" }
        ],
        command: [
          { required: true, message: "命令不能为空", trigger: "blur" },
          { max: 50, message: "命令长度不能超过50个字符", trigger: "blur" }
        ],
        remark: [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    const { videoId, videoBv } = this.$route.query
    if (!videoId || !videoBv) {
      this.$message.error('缺少必要的参数')
      return
    }
    this.getList()
  },
  methods: {
    /** 查询命令列表 */
    getList() {
      this.loading = true
      listCommand({
        ...this.queryParams,
        videoId: this.$route.query.videoId,
        videoBv: this.$route.query.videoBv
      }).then(response => {
        this.commandList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        videoId: null,
        videoBv: null,
        command: null,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.videoId = this.$route.query.videoId;
      this.form.videoBv = this.$route.query.videoBv;
      this.open = true;
      this.title = "添加视频关联指令";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCommand(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改视频关联指令";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCommand(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCommand(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除视频关联指令编号为"' + ids + '"的数据项？').then(function() {
        return delCommand(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/command/export', {
        ...this.queryParams
      }, `command_${new Date().getTime()}.xlsx`)
    },
    copyVariable() {
      const variable = '%pname%';
      navigator.clipboard.writeText(variable).then(() => {
        this.$message({
          message: '变量已复制到剪贴板',
          type: 'success',
          duration: 1500
        });
      }).catch(() => {
        // 如果剪贴板API不可用，使用传统方法
        const textarea = document.createElement('textarea');
        textarea.value = variable;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        this.$message({
          message: '变量已复制到剪贴板',
          type: 'success',
          duration: 1500
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.command-container {
  padding: 20px;

  .video-info-card {
    margin-bottom: 20px;
    border-radius: 12px;
    border: none;
    
    .video-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .header-left {
        display: flex;
        align-items: center;
        
        i {
          font-size: 24px;
          color: #00a1d6;
          margin-right: 10px;
        }
        
        .title {
          font-size: 18px;
          font-weight: 600;
          color: #18191c;
        }
      }
    }
    
    .video-content {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      
      .info-item {
        .label {
          color: #666;
          margin-right: 8px;
        }
        
        .value {
          color: #18191c;
          font-weight: 500;
        }
      }
    }
  }

  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .left-btns {
      display: flex;
      gap: 10px;
    }
  }

  .command-list {
    border-radius: 12px;
    border: none;
    
    .el-table {
      border-radius: 8px;
      overflow: hidden;
      
      &::before {
        display: none;
      }
    }
    
    .remark-text {
      color: #666;
    }
    
    .delete-btn {
      color: #ff4757;
    }
  }
}

.command-dialog {
  .el-dialog__body {
    padding: 30px 40px;
  }
  
  .command-tip {
    margin: -10px 0 15px 150px;
    padding: 8px 15px;
    background: #fff6f6;
    border-left: 4px solid #ff6b81;
    border-radius: 4px;
    display: flex;
    align-items: center;
    
    .copy-btn {
      margin-left: 10px;
      padding: 2px 8px;
      color: #ff6b81;
      font-size: 13px;
      
      &:hover {
        background: rgba(255, 107, 129, 0.1);
      }
      
      i {
        margin-right: 4px;
        font-size: 14px;
      }
    }
    
    i {
      color: #ff6b81;
      font-size: 16px;
      margin-right: 8px;
    }
    
    span {
      color: #666;
      font-size: 14px;
      
      code {
        background: #fff;
        color: #ff6b81;
        padding: 2px 6px;
        border-radius: 3px;
        margin: 0 2px;
        font-family: monospace;
        font-weight: bold;
        border: 1px solid #ffccd1;
      }
    }
  }
  
  .disabled-input {
    background-color: #f5f7fa;
    
    input {
      color: #909399;
    }
  }
  
  .command-input {
    input {
      font-family: monospace;
    }
  }
  
  .remark-input {
    textarea {
      font-family: system-ui;
    }
  }
  
  .el-form-item {
    margin-bottom: 25px;
  }
}

// B站风格的滚动条
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #99a9bf;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: #f6f7f8;
}
</style>
